package com.example.gymmanagebackend.controller;
import cn.hutool.json.ObjectMapper;
import com.example.gymmanagebackend.mapper.UserMapper;
import com.example.gymmanagebackend.pojo.Members;
import com.example.gymmanagebackend.pojo.RegisterRequest;
import com.example.gymmanagebackend.pojo.User;
import com.example.gymmanagebackend.service.MembersService;
import com.example.gymmanagebackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeParseException;

@RestController
@RequestMapping("/api/members") // 定义API的基本路径
public class MembersController {

    @Autowired
    private MembersService membersService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    // 获取所有会员信息
    @GetMapping
    public Page<Members> getAllMembers(@RequestParam(defaultValue = "0") int page,
                                       @RequestParam(defaultValue = "10") int size,
                                       @RequestParam(required = false) String search) {
        Pageable pageable = PageRequest.of(page, size);
        if (search != null && !search.isEmpty()) {
            return membersService.findBySearch(search, pageable);
        } else {
            return membersService.findAll(pageable);
        }
    }

    // 根据ID获取会员信息
    // 获取会员信息 by ID
    @GetMapping("/member/{id}")
    public Members getMemberById(@PathVariable Integer id) {
        return membersService.findMemberById(id);
    }

    // 获取会员信息 by Name
    @GetMapping("/memberByName/{name}")
    public Members getMemberByName(@PathVariable String name) {
        return membersService.findMemberByName(name);
    }

    @GetMapping("/{phone}")
    public Members getMemberByPhone(@PathVariable String phone) {
        return membersService.findMemberByPhone(phone);
    }

    // 添加会员信息
    @PostMapping("/addMember")
    public ResponseEntity<?> addMember(@RequestParam("name") String name,
                                       @RequestParam("gender") String gender,
                                       @RequestParam("birthday") String birthday,
                                       @RequestParam("phone") String phone,
                                       @RequestParam("registerDate") String registerDate,
                                       @RequestParam("cardType") String cardType,
                                       @RequestParam("expiryDate") String expiryDate) {
        Members member = new Members();
        member.setName(name);
        member.setGender(gender);
        member.setPhone(phone);

        try {
            member.setBirthday(LocalDate.parse(birthday));
            member.setRegisterDate(LocalDate.parse(registerDate));
            member.setExpiryDate(LocalDate.parse(expiryDate));
        } catch (DateTimeParseException e) {
            return ResponseEntity.badRequest().body("Invalid date format. Please use yyyy-MM-dd");
        }

        // 验证卡种是否合法
        if (!"次卡".equals(cardType) && !"月卡".equals(cardType) && !"季卡".equals(cardType) && !"年卡".equals(cardType)) {
            return ResponseEntity.badRequest().body("Card type must be '次卡', '月卡', '季卡', or '年卡'");
        }

        member.setCardType(cardType);

        try {
            int result = membersService.addMember(member);
            if (result > 0) {
                return ResponseEntity.ok("Member added successfully");
            } else {
                // 处理重复电话号码的情况
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("A member with this phone number already exists");
            }
        } catch (DuplicateKeyException e) {
            // 处理重复键异常
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("A member with this phone number already exists");
        }
    }

    // 更新会员信息
    @PutMapping("/{phone}")
    public ResponseEntity<?> updateMember(@PathVariable String phone, @RequestBody Members member) {
        member.setPhone(phone);
        int result = membersService.updateMember(member);
        if (result > 0) {
            return ResponseEntity.ok("Member updated successfully");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to update member");
        }
    }


    @DeleteMapping("/{name}")
    public ResponseEntity<?> deleteMemberByName(@PathVariable String name) {
        // 首先检查members表中是否存在该name
        Members member = membersService.findMemberByName(name);
        if (member != null) {
            // 删除members表中的数据
            membersService.deleteMemberByName(name);

            // 然后删除users表中对应的数据
            User user = userService.findUserByUsername(name);
            if (user != null) {
                userService.deleteUserById(user.getId());
            }

            return ResponseEntity.ok("会员及其用户信息删除成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("会员信息未找到");
        }
    }
    @CrossOrigin(origins = "http://localhost:8081")
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest registerRequest) {
        Members member = registerRequest.getMember();
        String name = member.getName(); // 使用 name 作为 username

        // 检查 name 是否已存在
        User existingUser = userMapper.findUserByUsername(name);
        if (existingUser != null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名已被占用");
        }

        // 添加会员到 Members 表
        membersService.addMember(member);

        // 创建用户信息
        User user = new User();
        user.setUsername(name); // 使用成员的 name 作为用户的 username
        user.setPassword(registerRequest.getPassword());
        user.setIdentify("mem"); // 标识为会员
        userService.addUser(user);

        return ResponseEntity.ok("注册成功");
    }
}